#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.${artifactId}.impl;

import com.alibaba.nacos.common.utils.JacksonUtils;
import ${package}.${artifactId}.DemoManager;
import ${package}.data.dal.es.ESDemoProductDAO;
import ${package}.data.dal.mysql.ItemProductDAO;
import ${package}.data.dataobject.DemoProductDO;
import ${package}.data.dataobject.ItemProductDO;
import ${package}.integration.OwnthinkClient;
import ${package}.integration.dto.KnowledgeDTO;
import org.elasticsearch.search.suggest.term.TermSuggestionBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.suggest.response.Suggest;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: shenyang
 * @CreateTime: 2022-10-07  09:07
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class DemoManagerImpl implements DemoManager {

    private static final Logger logger = LoggerFactory.getLogger(DemoManagerImpl.class);

    //    @Resource
    private ESDemoProductDAO esDemoProductDAO;

    @Resource
    private ItemProductDAO itemProductDAO;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    private OwnthinkClient ownthinkClient;

    @Resource
    private ElasticsearchOperations elasticsearchOperations;

    @Override
    public Page<DemoProductDO> findByProductName(String productName) {
        KnowledgeDTO knowledgeDTO = ownthinkClient.queryProductName(productName);
        logger.info("========================={}", JacksonUtils.toJson(knowledgeDTO));
        List<List<String>> knowledgeList = knowledgeDTO.getData();
        List<String> productNames = knowledgeList.stream().map(knowledge -> knowledge.get(0)).collect(Collectors.toList());


        SearchHits<DemoProductDO> byProductName = esDemoProductDAO.findByProductName(productName);
        Suggest suggest = byProductName.getSuggest();
        return esDemoProductDAO.findByProductNameIn(productNames, PageRequest.of(0, 100));

//        Criteria criteria = new Criteria("productName").is(productName);
//        Query query = new CriteriaQuery(criteria);
//        SearchHits<DemoProductDO> search = elasticsearchOperations.search(query, DemoProductDO.class);


//        *****************************************************************************
        //查询title字段中，包含 ”开发”、“开放" 这个字符串的document；相当于把"浦东开发开放"分词了，再查询；
//        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(productName).defaultField("productName");
//        SuggestBuilder suggestBuilder = new SuggestBuilder();
//        TermSuggestionBuilder termSuggestionBuilder = getTermSuggestionBuilder(productName);
//        suggestBuilder.addSuggestion("suggest", termSuggestionBuilder);
//        NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryStringQueryBuilder);
//        nativeSearchQuery.setSuggestBuilder(suggestBuilder);
//        SearchHits<DemoProductDO> search = elasticsearchOperations.search(nativeSearchQuery, DemoProductDO.class);
//        return null;
    }

    private static TermSuggestionBuilder getTermSuggestionBuilder(String productName) {
        TermSuggestionBuilder termSuggestionBuilder = new TermSuggestionBuilder("productName");
        termSuggestionBuilder.text(productName);
        termSuggestionBuilder.size(3); // 可选，指定建议结果的数量
        termSuggestionBuilder.maxTermFreq(0.5f); // 设置最大错误率
        return termSuggestionBuilder;
    }


    @Override
    public int importAll() {
        List<ItemProductDO> all = itemProductDAO.getAll();
        logger.info("数据总量：{}", all.size());
        List<DemoProductDO> esProductList = all.stream().map(DemoManagerImpl::getDemoProductDO).collect(Collectors.toList());
        Iterable<DemoProductDO> esProductIterable = esDemoProductDAO.saveAll(esProductList);
        Iterator<DemoProductDO> iterator = esProductIterable.iterator();
        int result = 0;
        while (iterator.hasNext()) {
            result++;
            iterator.next();
        }
        return result;
    }

    private static DemoProductDO getDemoProductDO(ItemProductDO itemProductDO) {
        DemoProductDO demoProductDO = new DemoProductDO();
        demoProductDO.setId(itemProductDO.getId().toString());
        demoProductDO.setProductName(
                itemProductDO.getProductName());
        demoProductDO.setDescription(itemProductDO.getDescription());
        demoProductDO.setBrandName("");
        demoProductDO.setPrice(itemProductDO.getMaxPrice());
        demoProductDO.setPicUrl(itemProductDO.getPicUrl());
        return demoProductDO;
    }

    @Override
    public int importProductById(Integer productId) {


        ItemProductDO itemProductDO = itemProductDAO.getById(productId);
        DemoProductDO demoProductDO = new DemoProductDO();
        demoProductDO.setId(itemProductDO.getId().toString());
        demoProductDO.setProductName(itemProductDO.getProductName());
        demoProductDO.setDescription(itemProductDO.getDescription());
        demoProductDO.setBrandName("苹果");
        demoProductDO.setPrice(itemProductDO.getMaxPrice());
        demoProductDO.setPicUrl(itemProductDO.getPicUrl());
        logger.info(JacksonUtils.toJson(demoProductDO));
        DemoProductDO save = esDemoProductDAO.save(demoProductDO);
        logger.info(JacksonUtils.toJson(save));
        return 1;
    }

    @Override
    public void delete(String id) {
        esDemoProductDAO.deleteById(id);
    }

    @Override
    public DemoProductDO create(String id) {
        DemoProductDO result = null;
        List<DemoProductDO> esProductList = null;
//        List<DemoProductDO> esProductList = productDao.getAllEsProductList(id);
        if (esProductList.size() > 0) {
            DemoProductDO esProduct = esProductList.get(0);
            result = esDemoProductDAO.save(esProduct);
        }
        return result;
    }

    @Override
    public void delete(List<String> ids) {
        if (!CollectionUtils.isEmpty(ids)) {
            List<DemoProductDO> esProductList = new ArrayList<>();
            for (String id : ids) {
                DemoProductDO esProduct = new DemoProductDO();
                esProduct.setId(id);
                esProductList.add(esProduct);
            }
            esDemoProductDAO.deleteAll(esProductList);
        }
    }
}
